import { _decorator, Collider2D, Component, Contact2DType, director, EventTouch, find, Input, input, instantiate, IPhysics2DContact, Label, math, Node, Prefab, profiler, resources, RigidBody2D, sp, Sprite, SpriteFrame, tween, UITransform, Vec2, Vec3, view } from 'cc';
import { PrefabsLoader } from '../Preload/PrefabsLoader';
import { Axe } from '../weapon/Axe';

const { ccclass, property } = _decorator;
@ccclass('Player')
export class Player extends Component {
    @property(Node)
    public player: Node = null; //人物节点 
    @property
    public minX: number = 0; // X轴最小值（左边界）
    @property
    public maxX: number = 0; // X轴最大值（右边界）
    private startPosition: Vec2 = null;  //触摸开始
    private endPosition: Vec2 = null; //触摸结束
    private moveDuration: number = 3.5; //移动距离
    public isTouch: boolean = false;  //是否开始触摸
    @property(sp.Skeleton)
    public skeleton: sp.Skeleton = null;   //人物动作

    @property(sp.Skeleton)
    public skeleton2: sp.Skeleton = null;   //人物得到奖励动作

    public autoAttack: boolean = true;  //控制自动发射武器

    throwInterval: number = 0.8;  // 攻击的时间间隔

    throwIntervalDecrease: number = 0;  // 每秒减少的间隔量
    minThrowInterval: number = 0.5;  // 攻击间隔的最小值
    private throwTimer: number = 0;  // 初始化攻击计时器

    static actions: string = "01gongji3";  //人物动作
    
    private rigidBody: RigidBody2D = null;
    // private boxCollider: BoxCollider2D = null;
    // private collider: Collider2D = null;

    public playerMove: boolean = true;

    public addDamage: number = 0//增加子弹伤害
    public addDistance: number = 0//增加子弹距离
    public addSpeed: number = 0//增加子弹速度
    private _originalPos: Vec3 = new Vec3();
    @property(Node)
    public mainCamera: Node = null;  // Camera 节点
    
    public chooseRewards: number = 0;//得到精英、boss宝箱次数
    public chooseBossReward: boolean = false;//是否得到终极boss奖励

    public doubleDamage: boolean = false;//是否得到武器伤害*2
    start() {
        // 记录摄像机原始位置
        Vec3.copy(this._originalPos, this.mainCamera.position);
        // 隐藏fps:
        profiler.hideStats();
        // 设置屏幕边界
        // this.minX = view.getVisibleSize().width * 0.16;
        // this.maxX = view.getVisibleSize().width* 0.74;
        this.minX = -230;
        this.maxX = 230;
        //隐藏  人物得到奖励特效
        this.node.getChildByName("skeleton").active = false;
        this.node.getChildByName("tx_huo").active = false;

        // 确保加载完成
        if (this.skeleton) {
            // 播放主角动作动画
            this.playAnimation('01daiji1', true); 
        }

        // 获取节点上的 RigidBody2D 组件
        this.rigidBody = this.node.getComponent(RigidBody2D);

        Player.actions = "01gongji3";  //人物动作
        this.throwTimer = this.throwInterval;  // 初始化攻击计时器
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            // collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
        // 获取当前节点的父节点
        const parentNode = this.node.parent;
        // 将当前节点移到父节点的最上层
        if (parentNode) {
            this.node.setSiblingIndex(parentNode.children.length - 1); // 设置为最后一个节点
        }
        //监听触摸事件
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    // 销毁时移除事件监听
    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

     // 触摸事件开始时调用
     private onTouchStart(event: EventTouch) {
        // 获取触摸点在屏幕上的位置
        // this.startPosition = event.getLocation();

        if (!this.playerMove) {
            return;
        }
        this.startPosition = event.getUILocation();  //触摸开始位置
        this.isTouch = true;

    }

    // 触摸事件结束时调用
    private onTouchEnd(event: EventTouch) {
        this.isTouch = false;
    }

    // 抛出斧子
    throwAxe(direX: number, direY: number) {

        PrefabsLoader.preload('prefab/monster/npc_2', (axe: Node) => {
            if (this.node == null) {
                return
            }
            this.node.parent.addChild(axe);
            // 设置斧子的初始位置，从人物的前方抛出
            axe.setWorldPosition(this.player.worldPosition.x + 30 + direX, this.player.worldPosition.y + 200, this.player.worldPosition.z);
            // axe.setWorldPosition(this.player.worldPosition.x, this.player.worldPosition.y + 200, this.player.worldPosition.z);
            // 设置斧子的飞行方向
            const axeScript = axe.getComponent(Axe);
            axeScript.setDirection(new Vec2(0, 1));  // 斧子向前飞行
            // axeScript.setDirection(new Vec2(direX, direY));  // 斧子向前飞行
            //增加攻击伤害
            if (this.addDamage < 1 && this.addDamage > 0) {
                axeScript.damage = Math.round(axeScript.damage * this.addDamage);
            } else {
                axeScript.damage += this.addDamage;
            }
            // //增加攻击距离
            axeScript.maxDistance += this.addDistance;
            //增加子弹速度
            axeScript.speed += this.addSpeed * 10;
        })
    }
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        this.zombieCol(selfCollider, otherCollider);
    }
    // 如果碰撞到的是僵尸
    zombieCol(selfCollider: Collider2D, otherCollider: Collider2D) {
        // 如果碰撞到的是  对于编号为2的碰撞器  他的识别的数字是2^2 也就是4 才可以被识别
        if ((otherCollider.node.name === 'npc_1' && otherCollider.group === 4) || (otherCollider.node.name === 'npc_2' && otherCollider.group === 4)) {
            const operateZombieScript = otherCollider.node.getComponent(operateZombie);
            let npc_hp = otherCollider.node.getChildByName("Label_hp").getComponent(Label).string;
            let player_hp = this.node.getChildByName("Label_hp").getComponent(Label).string;
            //  小怪血少  小怪死   人物血少  人物死
            if (parseInt(npc_hp) < parseInt(player_hp)) {
                operateZombieScript.takeDamage(parseInt(player_hp), "撞击");
                this.setPlayerHp(parseInt(npc_hp), true);
                // operateZombieScript.die();
            } else {
                this.setPlayerHp(parseInt(npc_hp), true);
                operateZombieScript.takeDamage(parseInt(player_hp), "撞击");
                // this.die();
            }
        }
    }
    // 播放人物动画
    playAnimation(animationName: string, loop: boolean = true) {
        if (this.skeleton) {
            this.skeleton.setAnimation(0, animationName, loop); 
        }
    }
}


